package com.common.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.account.mapper.AuUserMapper;
import com.common.account.service.IAuUserService;
import com.common.basis.entity.User;
import com.common.basis.oauth.AuUser;
import org.springframework.stereotype.Service;

import java.util.HashSet;

/**
 * 服务实现类
 *
 * @author wangguochao
 * @since 2020-01-06
 */
@Service
public class AuUserServiceImpl extends ServiceImpl<AuUserMapper, AuUser> implements IAuUserService {


    /**
     * 获取用户根据用户名
     *
     * @param userName 账号
     * @return 用户
     */
    @Override
    public AuUser findUserByName(String userName) {
        QueryWrapper<AuUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AuUser::getUserName, userName);
        return getOne(wrapper);
    }

    @Override
    public Boolean bindUserByPhone(String openId, String phone) {
        LambdaQueryWrapper<AuUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AuUser::getPhone, phone);
        int count = this.count(wrapper);
        if (count != 1) {
            return false;
        }
        LambdaUpdateWrapper<AuUser> wrapper1 = Wrappers.lambdaUpdate();
        wrapper1.eq(AuUser::getPhone, phone)
                .set(AuUser::getOpenId, openId);
        return this.update(wrapper1);
    }

    @Override
    public User getUserByName(String username) {
        AuUser user = this.findUserByName(username);
        User user1 = new User();
        user1.setPassword(user.getPassword());
        user1.setUsername(user.getUserName());
        user1.setAuthorities(new HashSet<>());
        user1.setTenantId(user.getTenantId());
        user1.setUserId(user.getId());
        user1.setAccountNonExpired(true);
        user1.setAccountNonLocked(true);
        user1.setCredentialsNonExpired(true);
        user1.setEnabled(true);
        return user1;
    }


}
